package com.dkm.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dkm.entity.Role;
import com.dkm.service.RoleService;
import com.dkm.util.LayuiJsonUilt;
import com.dkm.util.ResultUtil;

@RestController
@RequestMapping("/role")
public class RoleController {

	//注入角色业务层
	@Autowired
	private RoleService roleService;
	
	@GetMapping
	@RequiresPermissions(value = "role:query")
	public LayuiJsonUilt<Role> findAllRoles(Role role,LayuiJsonUilt<Role> lj) {
		//创建分页对象
		Pageable pageable=PageRequest.of(lj.getPage(), lj.getLimit());
		//获取page对象
		Page<Role> page=roleService.findAllRoles(role, pageable);
		//设置数据
		lj.setData(page.getContent());
		//设置数据长度
		lj.setCount(page.getTotalElements());
		
		return lj;
	}
	//添加角色
	@PostMapping
	@RequiresPermissions(value = "role:add")
	public ResultUtil addRole(Role role) {
		
		return roleService.saveAndFlushRole(role);
	}
	//修改角色
	@PutMapping
	@RequiresPermissions(value = "role:update")
	public ResultUtil updateRole(Role role) {
		
		return roleService.saveAndFlushRole(role);
	}
	
	//删除角色
	@DeleteMapping
	@RequiresPermissions(value = "role:delete")
	public ResultUtil deleteRole(String role_id) {
		
		return roleService.deleteRole(role_id);
	}
	
	@GetMapping("/giveRoleSetPermission")
	@RequiresPermissions(value = "role:giveRoleSetPermission")
	public ResultUtil giveRoleSetPermission(String role_id,HttpServletRequest request) {
		//获取模块和权限的id集合
		String[] moduleids=request.getParameterValues("moduleids[]");
		List<Integer> moduleidList=null;
		List<String> permissionidList=null;
		if(moduleids!=null) {
			moduleidList=new ArrayList<Integer>();
			for(int i=0;i<moduleids.length;i++) {
				moduleidList.add(Integer.parseInt(moduleids[i]));
			}
			//return new ResultUtil(-1, "模块数据异常", null);
		}
		String[] permissionids=request.getParameterValues("permissionids[]");
		if(permissionids!=null) {
			permissionidList=new ArrayList<String>(Arrays.asList(permissionids));
		}
		return roleService.giveRoleSetPermission(role_id, moduleidList, permissionidList);
	}
}
